<?php


namespace frontend\models\cyf;


use yii\db\ActiveRecord;

class FlashSale extends ActiveRecord
{
    public static function tableName()
    {
        return '2008a_flash_sale';
    }

    /**
     * 关联商品表
     * @return \yii\db\ActiveQuery
     */
    public function getGoods()
    {
        return $this->hasOne(Goods::class,['id'=>'goods_id']);
    }

    /**
     * 秒杀商品列表
     * @cyf
     */
    public static function list()
    {
        return self::find()->select('*')->asArray()->all();
    }
    /**
     * 添加秒杀商品
     * @param $params
     * @return bool
     * @cyf
     */
    public static function create($params)
    {
        $flahsale = new FlashSale();
        $flahsale->key = $params['key'];
        $flahsale->goods_id = $params['goods_id'];
        $flahsale->name = $params['name'];
        $flahsale->is_top = $params['is_top'];
        $flahsale->stocks = $params['stocks'];
        $flahsale->pic_url = $params['pic_url'];
        $flahsale->flash_price = $params['flash_price'];
        $flahsale->status = $params['status'];
        return $flahsale->save();

    }

    /**
     * 秒杀商品
     * @cyf
     */
    public static function flashOne($id)
    {
        return self::findOne($id)->toArray();
    }

    /**
     * 秒杀商品详情
     * @param $goodsId
     */
    public static function detail($goodsId)
    {
        return self::find()->joinWith('goods')
            ->asArray()->all()[0];

    }

    /**
     * 秒杀商品库存减一
     * @param $goods_id
     * @return bool
     */
    public static function killGoods($id)
    {
        $goods = self::findOne($id);
        $goods->stocks = $goods->stocks -1;
        return $goods->save();
    }
}